﻿//(c) Alexandru Ghiondea, 2011
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

namespace JSONDotNET
{
    public static class MyTypeConverter
    {
        /// <summary>
        /// Wraps a given value in a Nullable type
        /// </summary>
        /// <param name="value"></param>
        /// <param name="innerType"></param>
        /// <returns></returns>
        public static object AsNullable(this object value, Type innerType)
        {
            var retObj = Activator.CreateInstance(typeof(Nullable<>).MakeGenericType(innerType));
            if (value == null)
                retObj = null;
            else
                retObj = value;
            return retObj;
        }

        /// <summary>
        /// Changes the type of the value to the requested type
        /// </summary>
        /// <param name="value"></param>
        /// <param name="toType"></param>
        /// <returns></returns>
        public static object ChangeType(this object value, Type toType)
        {
            if (toType == typeof(byte))
                return Convert.ToByte(value);
            if (toType == typeof(sbyte))
                return Convert.ToSByte(value);
            if (toType == typeof(short))
                return Convert.ToInt16(value);
            if (toType == typeof(ushort))
                return Convert.ToUInt16(value);
            if (toType == typeof(int))
                return Convert.ToInt32(value);
            if (toType == typeof(uint))
                return Convert.ToUInt32(value);
            if (toType == typeof(long))
                return Convert.ToInt64(value);
            if (toType == typeof(ulong))
                return Convert.ToUInt64(value);

            if (toType == typeof(float))
                return Convert.ToSingle(value);
            if (toType == typeof(double))
                return Convert.ToDouble(value);

            if (toType == typeof(decimal))
                return Convert.ToDecimal(value);

            //in other cases, do nothing
            return value;
        }
    }
}
